﻿using System;
using System.Text.RegularExpressions;
using com.yoozoo.gta.Extension.UGUI.ScreenOrientationEx;

#if UNITY_EDITOR
using UnityEditor;
#endif

using UnityEngine;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Extension.UGUI.ScreenOrientation.Adapter
{
    //生成YImageAdaptConfiger
    [Serializable]
    public class YImageAdaptConfiger
    {
        public string spriteName;
        public Color color = Color.white; // 新增的Color属性，设置默认值为白色

        public bool mComponentEnable = true;

        //重写Equals方法
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }

            YImageAdaptConfiger other = (YImageAdaptConfiger) obj;
            // Compare spriteName properties
            if (spriteName != other.spriteName)
            {
                return false;
            }

            // Compare color properties
            if (color != other.color)
            {
                return false;
            }

            // Compare color properties
            if (mComponentEnable != other.mComponentEnable)
            {
                return false;
            }

            return true;
        }

        //重写GetHashCode方法
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    [DisallowMultipleComponent]
    public class YImageAdapter : AdaptBase<YImageAdaptConfiger, YImage>
    {
        private YImageWrap mImageWrap;

        protected override void CopyProperty(YImageAdaptConfiger config)
        {
            base.CopyProperty(config);
#if UNITY_EDITOR
            if (mComponent.sprite != null && !mComponent.clearOnSave)
            {
                var path = AssetDatabase.GetAssetPath(mComponent.sprite);
                config.spriteName = path;
            }
            else
            {
                if (mComponent.sprite == null && mComponent.clearByAdapter && config.spriteName != string.Empty)
                {
                    return;
                }

                config.spriteName = string.Empty;
            }

            if (CheckNameValid(config.spriteName))
            {
                Debug.LogError($"YImageAdapter 路径有误，请检查: {EditorExtension.HierarchyHelper.GetHierarchyPath(transform)}");
                // EditorUtility.DisplayDialog("YImageAdapter 使用了Arts错误路径提示",
                //     "原因: 不能使用Arts下资源路径 \n \n 修改方法: 复制资源方到ResourcesAssets路径下 \n \n 操作结果: 本次修改结果无效不会保存",
                //     "确定");
                mComponent.sprite = null;
                config.spriteName = string.Empty;
            }

            config.color = mComponent.color;
            config.mComponentEnable = mComponent.enabled;
            if (!config.mComponentEnable)
            {
                config.spriteName = string.Empty;
            }
#endif
        }

        private const string resourcePath = "Assets/Resources/";

        protected override void ApplyConfig(YImageAdaptConfiger config)
        {
            base.ApplyConfig(config);
            mComponent.enabled = config.mComponentEnable;
            mComponent.color = config.color;
            if (mComponent.sprite && mComponent.sprite.name == config.spriteName)
            {
                return;
            }

            mComponent.sprite = null; //先清理一下，防止挂了错误的朝向贴图，导致的闪一下问题
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                var sp = AssetDatabase.LoadAssetAtPath<Sprite>(config.spriteName);
                mComponent.sprite = sp;
                mComponent.color = config.color;
                return;
            }

            mComponent.clearByAdapter = false;
#endif
            if (config.spriteName.Contains(resourcePath))
            {
                var spPath = config.spriteName.Replace(resourcePath, "");
                spPath = spPath.Replace(".png", "");
                var sp = Resources.Load<Sprite>(spPath);

                mComponent.sprite = sp;
            }
            else
            {
                if (mImageWrap == null)
                {
                    mImageWrap = YImageWrap.Get(mComponent);
                    mImageWrap.LoadSync(); //横竖版优先加载
                    //mImageWrap.priority = int.MaxValue;
                }

                if (config.spriteName == string.Empty || config.spriteName.Contains("Resources/unity_builtin_extra"))
                {
                    mComponent.sprite = null;
                    mImageWrap.spriteName = string.Empty;
                }
                else
                {
                    mImageWrap.spriteName = config.spriteName;
                }
            }
        }

        protected new void OnDestroy()
        {
            base.OnDestroy();
            if (mImageWrap != null)
            {
                mImageWrap.Release();
                mImageWrap = null;
            }
        }
#if UNITY_EDITOR
        public bool CheckYImagePath(out string landscapeName, out string portraitName)
        {
            landscapeName = string.Empty;
            portraitName = string.Empty;
            if (mComponent == null)
            {
                UnityEngine.Debug.LogError($"YimageAdapter mComponent is null {ScenePathGameObject(gameObject)}");
                return false;
            }

            if (CheckNameValid(LandscapeConfig.spriteName))
            {
                Debug.LogError($"YImageAdapter 路径有误，请检查: {ScenePathGameObject(gameObject)}");
                landscapeName = LandscapeConfig.spriteName;
                return false;
            }

            if (CheckNameValid(PortraitConfig.spriteName))
            {
                Debug.LogError($"YImageAdapter 路径有误，请检查: {ScenePathGameObject(gameObject)}");
                portraitName = PortraitConfig.spriteName;
            }

            return true;
        }
        private string ScenePathGameObject(GameObject gameObject)
        {
            if(gameObject == null)
                return "gameObject is null";
            
            //获取gameobject到场景的路径
            string path = gameObject.name;
            Transform parent = gameObject.transform.parent;
            while (parent != null)
            {
                path = parent.name + "/" + path;
                parent = parent.parent;
            }
            return path;
        } 
        public YImage GetComponent()
        {
            return mComponent;
        }

        private bool CheckNameValid(string input)
        {
            return Regex.IsMatch(input, @"[\u4e00-\u9fff]") || input.Contains("Arts/");
        }

        public void ClearYImage()
        {
            if (mComponent.sprite != null && !mComponent.clearByAdapter)
            {
                mComponent.sprite = null;
                mComponent.spriteName = null;
                mComponent.clearByAdapter = true;
                if (LandscapeConfig.color == PortraitConfig.color)
                {
                    mComponent.cullNoneSprite = true;
                }
            }
        }

        public string GetPortraitImagePath()
        {
            return PortraitConfig?.spriteName ?? "";
        }

        public string GetLandscapeImagePath()
        {
            return LandscapeConfig?.spriteName ?? "";
        }
#endif
    }
}